<?php

/**

	
	websocket 基类
	
	websocket 服务
	websocket协议是基于tcp的一种新的网络协议，它实现了浏览器与服务器的双工通信，-允许服务器主动发送信息给客户端
	
	为什么需要websocket
		http的通信只能由客户端发起
		
	websocket特点
		1.建立在TCP协议之上
		2.性能开销小通信高效
		3.客户端可以与任意服务器通信
		4.协议标识符 ws wss
		5.持久化网络通信协议		
	
*/


class  WebSocket{
	public $host = "0.0.0.0";
	public $port = 8812;
	
	public $ws = null;
	public function __construct(){
		
		$this->ws = new swoole_websocket_server($this->host,$this->port);
		
		/** */
		$this->ws->set([
			'worker_num'=>2,
			'task_worker_num'=>2
		]);
		
		
		$this->ws->on('open',array($this,"onOpen"));
		$this->ws->on('message',array($this,"onMessage"));
		
		// 在onTask函数中 return字符串，表示将此内容返回给worker进程。worker进程中会触发onFinish函数
	
		$this->ws->on('task',array($this,"onTask"));
		$this->ws->on('finish',array($this,"onFinish"));
		
		$this->ws->on('close',array($this,"onClose"));
		
		
		
		$this->ws->start();
	}
	
	/**
     * 监听ws连接事件
     * @param $ws
     * @param $request
     */
	public function onOpen($ws, $frame){
		echo "client number :".$frame->fd;
	}
	
	/**
     * 监听ws消息事件
     * @param $ws
     * @param $frame
     */
	public function onMessage($serv,$frame){
		echo "ser-push-message : {$frame->data} \n";
		
		$data = [
			'task' => 1,
            'fd' => $frame->fd,
		];
		
		$serv->task($data);
		
		$serv->push($frame->fd," this is server ");
	}
	
	
	/**
		在task_worker进程内被调用
		
	*/
	public function onTask($serv,$taskId, $workerId, $data){
		
		$serv->push($data['fd'],'task 的 发送的信息');
		
		return "task msg";
	}
	
	
	public function onFinish($serv,$task_id,$data){
		echo "result $data \n ";
	}
	
	
	/**
	* close
	* @param $ws
    * @param $frame
	*/
	public function onClose($ws, $fd){	
		echo "close client {$fd} ";
	}
	
}



$ws = new WebSocket();







